import axios from 'axios';
import { useUserStore } from '@/store/user'
import router from '@/router';
import { ElMessage } from 'element-plus';
// 创建实例
const instance = axios.create({
  baseURL: 'http://localhost:4000/api',
  timeout: 3000
})

// 请求拦截器
instance.interceptors.request.use((config) => {
  const { token } = useUserStore()
  // 设置 token
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
}, (error) => {
  return Promise.reject(error)
})

const RESPONSE_CODE = {
  success: 10000, // 操作成功
  authorize: 401, // 未认证
}

// 相应拦截器
instance.interceptors.response.use((response) => {
  const { data: { code }, status } = response
  if (code === RESPONSE_CODE.success) {
    return response.data
  }
  return response
}, (error) => {
  const userStore = useUserStore()
  if (RESPONSE_CODE.authorize === error.status) {
    // 未认证
    ElMessage.error(error.response.data.message)
    // 清空相关信息
    userStore.logout()
    router.push(`/login?redirectUrl=${router.currentRoute.value.path}`)
  }
  return Promise.reject(error)
})

export default instance